#include "calServer.hpp"
#include <iostream>

#include <memory>
#include <string>
using namespace std;
using namespace Server;

// ./tcpServer 8080

// req一定是一个处理好的完整的请求对象
// 根据req做业务处理，填充resp

bool cal(const Request &req, Response &resp)
{
    resp.exitcode = OK;
    resp.result = OK;

    switch (req.op)
    {
    case '+':
        resp.result = req.x + req.y;
        break;
    case '-':
        resp.result = req.x - req.y;
        break;
    case '*':
        resp.result = req.x * req.y;
        break;
    case '/':
    {
        if (req.y == 0)
            resp.exitcode = DIV_ZERO;
        else
            resp.result = req.x / req.y;
    }
    break;
    case '%':
    {
        if (req.y == 0)
            resp.exitcode = MOD_ZERO;
        else
            resp.result = req.x % req.y;
    }
    break;
    default:
        resp.exitcode = OP_ERROR;
        break;
    }
    return true;
}

static void Usage(const string &proc)
{
    std::cout << "\nUsage: \n\t" << proc << " localport\n"
              << std::endl;
    exit(USAGE_ERR);
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    std::unique_ptr<calServer> tsvr(new calServer(port));
    tsvr->initServer();
    tsvr->run(cal);
    return 0;
}